import { mapManager } from '../MapManager';
import MapFeature from './MapFeature'
import * as events from '../event';
import * as drag from '../drag';
import * as api from '../../../util/api';
import { Point, Polygon } from 'ol/geom';
import Feature from 'ol/Feature';
import * as ftypes from '../featureTypes'; //地图上各个点的类型
import { message } from 'ant-design-vue';
import Base from './base';
import BaseStyle from '../style/baseStyle';

function newCoordinatesGroup(p) {
  try {
    var obj = JSON.parse(p);
    return obj;
  } catch (e) {
    return null
  }
}


/**
 * 基地中心点对象
 */
class BaseMarker extends MapFeature {

  static MARKER__INDEX = 0;
  static moveInteraction = null;
  static onAddFeature = null;


  /**
   * 
   * @param {Feature} f 
   * @param {import('../../../util/typedef').BaseInfo} valueObject - 基地信息
   */
  constructor(f, valueObject) {
    super(f);
    if (valueObject) {
      this.setValueOjbect(valueObject);
    } else {
      if(f.get("_valueobject") == undefined){
        this.setValueOjbect({});
      }
    }
  }

  hasBounds() {
    return this.feature.get('_hasBounds');
  }

  setBounds(val) {
    this.feature.set('_hasBounds', val);
  }


  /**
   * 开始画基地中心点
   */
  static beginDraw() {
    MapFeature.innerDraw({
      type: 'Point',
      style: BaseStyle.getMarkerStyle()
    }, (evt) => {

      evt.feature.set(ftypes.FTYPE, ftypes.MARKER);
      evt.feature.setStyle(BaseStyle.getMarkerStyle());
      var geo = evt.feature.getGeometry();
      var latlng = geo.getCoordinates();
      evt.feature.set("index_", BaseMarker.MARKER__INDEX);
      evt.feature.setId("temp_");

      if (mapManager.getLayers().baseSource.getFeaturesAtCoordinate(latlng).length > 0) {//验证基地中心点是否在别的基地中                 
        evt.feature.set("deleted", true); //标记已经删除，后面添加到source后再删除
        message.error("基地重复,请重新规划!");
        return false;
      }
      BaseMarker.MARKER__INDEX++;
    });

  }


  doEdit() {
    //通知打开窗口编辑
    events.fire(events.types.onAddBaseMarker, { type: 'update', data: this.feature });
    var id = this.feature.getId();
    this.feature.setStyle(BaseStyle.getMarkerStyle());
    //可以移动点 
    BaseMarker.moveInteraction = new drag.Drag();
    drag.setOpts({
      moveTarget: id,
      backCoordinate: this.feature.getGeometry().clone().getCoordinates(),
      onMoved: (f) => {
        this.feature = f;
        events.fire(events.types.onAddBaseMarker, { type: 'moved', data: f });
      }
    });
    mapManager.addInteraction(BaseMarker.moveInteraction);
  }

  static cancelEdit() {
    if (BaseMarker.moveInteraction != null) {
      mapManager.removeInteraction(BaseMarker.moveInteraction);
    }
  }

  /**
   * 保存成功
   */
  static saveOk(feature) {
    mapManager.getLayers().markerSource.addFeature(feature);
    var baseInfo = (new BaseMarker(feature)).getValueObject();
    feature.setStyle(BaseStyle.getMarkerStyle(baseInfo));
    mapManager.clearDrawSource();
  }

  static initData(callback) {
    api.get(api.ZYGL_BASE_LIST, (resp) => {
      var bases = resp.data;
      for (var i = 0, j = bases.length; i < j; i++) {
        //基地中心标记
        var base = bases[i];
        var marker = new Feature({
          ftype: ftypes.MARKER,
          index_: i,
          base_id_: base.id,
          name_: base.name, 
          geometry: new Point([base.longitude, base.latitude])
        });
        var markerWrapper = new BaseMarker(marker,base);
        markerWrapper.setBounds((base.coordinateGroup == null ? false : true));        
        markerWrapper.setType(ftypes.MARKER);
        marker.setId(BaseMarker.getMarkerIdByBaseId(base.id));
        marker.setStyle(BaseStyle.getMarkerStyle(base));
        mapManager.getLayers().markerSource.addFeature(marker);

        //画定基地范围
        var coordinateGroup = newCoordinatesGroup(base.coordinateGroup);
        base.latlngBounds = coordinateGroup;
        if (base.latlngBounds != null && base.latlngBounds.coordinates != null && base.latlngBounds.coordinates.length > 0) {
          var polygon = new Feature({
            ftype: ftypes.BASE,
            geometry: new Polygon(base.latlngBounds.coordinates),
            name: base.name
          });

          var baseFeatureWrapper = new Base(polygon,base);
          baseFeatureWrapper.setId(Base.getFeatureIdByBaseId(base.id)); 
          polygon.setStyle(BaseStyle.getBorderStyleStyle(base));
          mapManager.getLayers().baseSource.addFeature(polygon);
        }
      }

      mapManager.getLayers().markerVector.setZIndex(10);
      mapManager.getLayers().baseVector.setZIndex(1);
      BaseMarker.MARKER__INDEX = bases.length;
      Base.BASE__INDEX = bases.length;
      callback({ baseList: bases });

    })
  }


  static getMarkerIdByBaseId(baseId) {
    return "marker_" + baseId;
  }

}

export default BaseMarker;